<%@ page import="com.silverhaze.web.WebConstants" %>
<%@ page import="com.silverhaze.web.data.wot.WoTPlayer" %>
<%@ page import="com.silverhaze.web.util.EntityManageUtil" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    String url = request.getParameter("url");
    String player = request.getParameter("player");
    List<WoTPlayer> woTPlayers = EntityManageUtil.load(WoTPlayer.class);

    if (player != null && url != null) {
        List<WoTPlayer> suitablePlayers = new ArrayList<WoTPlayer>();

        for (WoTPlayer woTPlayer : woTPlayers) {
            if (woTPlayer.getUser().equals(player)) {
                suitablePlayers.add(woTPlayer);
            }
        }

        if (suitablePlayers.isEmpty()) {
            WoTPlayer newPlayer = new WoTPlayer();

            newPlayer.setUser(player);
            newPlayer.setWotProfileUrl(url);

            EntityManageUtil.persist(newPlayer);

%>

<b>new player [<%=player%> => <%=url%>] added</b>

<%
} else {
    for (WoTPlayer tPlayer : suitablePlayers) {
        tPlayer.setWotProfileUrl(url);
        EntityManageUtil.update(tPlayer);
    }
%>

<b>player <%=player%> updated with url [<%=url%>]</b>

<%
        }
    }

    woTPlayers = EntityManageUtil.load(WoTPlayer.class);
%>

<html>
<head>
    <title></title>
    <link rel="stylesheet" href="style/style.css"/>
</head>
<body>
<form action="manage.jsp" method="POST">
    Player name: <input type="text" name="player">
    WoT profile: <input type="text" name="url">
    <input type="submit" value="update">
</form>


<table border="1">
    <tr>
        <td>player</td>
        <td>wot profile</td>
        <td>last update</td>
        <td>registration</td>
        <td></td>
    </tr>
    <%
        for (WoTPlayer woTPlayer : woTPlayers) {
    %>
    <tr>
        <td><%=woTPlayer.getUser()%>
        </td>
        <td><%=woTPlayer.getWotProfileUrl()%>
        </td>
        <td><%=woTPlayer.getLastUpdateTime()%>
        </td>
        <td><%=woTPlayer.getRegistrationDate()%>
        </td>
        <td>[<a href="manage.jsp?remove=<%=woTPlayer.getId()%>">remove</a>]</td>
    </tr>
    <%
        }
    %>
</table>

</body>
</html>